package com.huanhuanzhang.www;

public class Uti {
	private static double EARTH_RADIUS = 6371.393;

	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	public static double GetDistance(double lat1, double lng1, double lat2, double lng2) {
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);
		double s = 2 * Math.asin(Math.sqrt(
				Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 1000);
		return s;
	}

	public static double getDistance(double long1, double lat1, double long2, double lat2) {
		double a, b, R;
		R = 6378137; // 地球半径
		lat1 = lat1 * Math.PI / 180.0;
		lat2 = lat2 * Math.PI / 180.0;
		a = lat1 - lat2;
		b = (long1 - long2) * Math.PI / 180.0;
		double d;
		double sa2, sb2;
		sa2 = Math.sin(a / 2.0);
		sb2 = Math.sin(b / 2.0);
		d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) * Math.cos(lat2) * sb2 * sb2));
		return d;
	}

	public static void main(String[] args) {
		System.out.println(GetDistance(39.90, 116.40, 31.23, 121.47));
		System.out.println(getDistance(116.40, 39.90, 121.47, 31.23));
		System.out.println(getAngle1(39.90, 116.40, 31.23, 121.47));
		System.out.println(gps2d(39.90, 116.40, 31.23, 121.47));
	//	System.out.println(GetAzimuth(39.90, 116.40, 31.23, 121.47));

	

	}

	public static double getAngle1(double lat_a, double lng_a, double lat_b, double lng_b) {
		double y = Math.sin(lng_b - lng_a) * Math.cos(lat_b);
		double x = Math.cos(lat_a) * Math.sin(lat_b) - Math.sin(lat_a) * Math.cos(lat_b) * Math.cos(lng_b - lng_a);
		double brng = Math.atan2(y, x);
		brng = Math.toDegrees(brng);
		if (brng < 0)
			brng = brng + 360;
		return brng;
	}

	public static double gps2d(double lat_a, double lng_a, double lat_b, double lng_b) {

		double d = 0;

		lat_a = lat_a * Math.PI / 180;

		lng_a = lng_a * Math.PI / 180;

		lat_b = lat_b * Math.PI / 180;

		lng_b = lng_b * Math.PI / 180;

		d = Math.sin(lat_a) * Math.sin(lat_b) + Math.cos(lat_a) * Math.cos(lat_b) * Math.cos(lng_b - lng_a);

		d = Math.sqrt(1 - d * d);

		d = Math.cos(lat_b) * Math.sin(lng_b - lng_a) / d;

		d = Math.asin(d) * 180 / Math.PI;

		return d;

	}

	public static double GetAzimuth(double lon1, double lat1, double lon2, double lat2) {
		lat1 = rad(lat1);
		lat2 = rad(lat2);
		lon1 = rad(lon1);
		lon2 = rad(lon2);
		double azimuth = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
		azimuth = Math.sqrt(1 - azimuth * azimuth);
		azimuth = Math.cos(lat2) * Math.sin(lon2 - lon1) / azimuth;
		azimuth = Math.asin(azimuth) * 180 / Math.PI;
		if (Double.isNaN(azimuth)) {
			if (lon1 < lon2) {
				azimuth = 90.0;
			} else {
				azimuth = 270.0;
			}
		}
		return azimuth;
	}
}
